<style lang="less">
@import "../../styles/common.less";
.operate-column .ivu-btn-text{
    color:#008cd6;
}
.operate-column .ivu-btn-text:focus{
    box-shadow: none;
}
.device-detail-dialog{
    .device-line{
        display: flex;
        justify-content: space-between;
        margin-bottom:10px;
        font-size:12px;
        line-height:20px;
        .item{
            flex:1 0 33.3%;
        }
        .item2{
            flex:2 0 66.6%;
        }
    }
    .ivu-btn:first-child{
        display: none;
    }
}
.alarm-setting-dialog{
    .alarm-line{
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        .item{
            margin-right: 30px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            span{
                margin-right:4px;
            }
        }
    }
}
</style>

<template>
  <div>
    <Row type="flex" justify="space-between">
      <Row>
        <Input
          v-model.trim="queryForm.ipc_id"
          @on-enter="loadTableData"
          clearable
          placeholder="请输入设备id"
          style="width: 150px;margin-right:3px"
        ></Input>
        <Input
          v-model.trim="queryForm.d_nm"
          clearable
          @on-enter="loadTableData"
          placeholder="请输入设备名称"
          style="width: 150px;margin-right:3px"
        ></Input>
        <Button type="primary" @click="loadTableData">搜索</Button>
        <!-- <Button type="warning" style="margin-right:10px" @click="emptyFeature">清空特征值底库</Button>
        <Button type="primary" @click="syncFeature">同步特征值底库</Button> -->
      </Row>
      <Row>
        <Dropdown @on-click="handleAddIPC">
          <Button type="primary">
            新建
            <Icon type="arrow-down-b"></Icon>
          </Button>
          <DropdownMenu slot="list">
            <!-- <DropdownItem name="HobotSmart_X1S">旭日_X1S</DropdownItem>
            <DropdownItem name="RTSP_Video">视频流_URL</DropdownItem>
            <DropdownItem name="DahuaNormal">视频流_大华</DropdownItem>
            <DropdownItem name="HobotSmart_X1">旭日_X1</DropdownItem> -->

            <!-- 虚假的巨龙抓拍相机 -->
            <!-- <DropdownItem name="JulongSmart_3519">巨龙抓拍相机</DropdownItem> -->

            <!-- 真实的巨龙抓拍相机 -->
            <DropdownItem name="Julong_jHD23">巨龙抓拍相机_jHD23</DropdownItem>

          </DropdownMenu>
        </Dropdown>
        <!-- <Button icon="ios-plus-outline" type="primary" @click="showAddIpcModal">新建</Button> -->
      </Row>
    </Row>
    <Table class="margin-top-10" ref="ipcTable" :columns="ipcColumn" :data="ipcDataList"></Table>
    <AddIPCModal ref="addIpc" :update_callback="onIpcUpdate"/>
    <AddGuardModal ref="addGuard" :update_callback="onIpcUpdate"/>
    <AddIPCModalDahua ref="addIPCDahua" :update_callback="onIpcUpdate"/>
    <AddIPCModalHobotSmartX1 ref="addIPCHobotSmartX1" :update_callback="onIpcUpdate"/>
    <!-- <AddIPCModalJulongSmart3519 ref="addIPCJulongSmart3519" :update_callback="onIpcUpdate"/> -->
    <AddIPCModalJulongJHD23 ref="addIPCModalJulongJHD23" :update_callback="onIpcUpdate"/>
    <AddIPCModalHobotSmartX1S ref="addIPCHobotSmartX1S" :update_callback="onIpcUpdate"/>
    <AddIPCModalRTSP ref="addIPCHobotRTSP" :update_callback="onIpcUpdate"/>


    <!-- 巨龙设备操作 -->
    <!-- 设备详情 -->
    <Modal class-name="device-detail-dialog" width="600" v-model="deviceDetailModal" title="设备详情">
        <div class="device-line">
            <div class="item">
                <label>序列号:</label>
                <span>{{currentDevice.device_id}}</span>
            </div>
            <div class="item">
                <label>UUID:</label>
                <span>{{currentDevice.device_uuid}}</span>
            </div>
            <div class="item">
                <label>Mac地址:</label>
                <span>{{currentDevice.device_mac}}</span>
            </div>
        </div>
        <div class="device-line">
            <div class="item">
                <label>设备类型:</label>
                <span>{{currentDevice.ipc_type}}</span>
            </div>
            <div class="item">
                <label>通道数:</label>
                <span>{{currentDevice.channel_num}}</span>
            </div>
            <div class="item">
                <label>页面版本:</label>
                <span>{{currentDevice.web_version}}</span>
            </div>
        </div>
        <div class="device-line">
            <div class="item">
                <label>主程序版本:</label>
                <span>{{currentDevice.core_version}}</span>
            </div>
            <div class="item">
                <label>版本日期:</label>
                <span>{{currentDevice.version_date}}</span>
            </div>
            <div class="item">
                <label>HTTP协议版本:</label>
                <span>{{currentDevice.http_version}}</span>
            </div>
        </div>
        <div class="device-line">
            <div class="item">
                <label>HTTP版本日期:</label>
                <span>{{currentDevice.http_date}}</span>
            </div>
            <div class="item2">
                <label>注册Session:</label>
                <span>{{currentDevice.register_session}}</span>
            </div>
        </div>
    </Modal>
    <!-- 人脸识别报警设置 -->
    <Modal class-name="alarm-setting-dialog" width="600" v-model="alarmSettingModal" title="人脸识别报警设置">
        <div class="alarm-line">
            <div class="item"><span>报警开关</span><i-switch :false-value="2" :true-value="1" v-model="currentAlarmDevice.alarm_switch"></i-switch></div>
            <div class="item"><span>黑名单报警</span><i-switch :false-value="2" :true-value="1" v-model="currentAlarmDevice.black_alarm_switch"></i-switch></div>
            <div class="item"><span>白名单报警</span><i-switch :false-value="2" :true-value="1" v-model="currentAlarmDevice.white_alarm_switch"></i-switch></div>
            <div class="item"><span>IO输出</span><i-switch :false-value="2" :true-value="1" v-model="currentAlarmDevice.io_switch"></i-switch></div>
            <div class="item">
                <RadioGroup v-model="currentAlarmDevice.io_type">
                    <Radio :label="1" :disabled="currentAlarmDevice.io_switch!==1">持续输出</Radio>
                    <Radio :label="2" :disabled="currentAlarmDevice.io_switch!==1">脉冲输出</Radio>
                </RadioGroup>
            </div>
            <div class="item">
                <span>报警持续输出时间(s)</span>
                <InputNumber :max="10000" :min="1" v-model="currentAlarmDevice.alarm_duration"></InputNumber>
            </div>
            <div class="item">
                <span>IO输出状态类型</span>
                <RadioGroup v-model="currentAlarmDevice.io_status_type">
                    <Radio :label="1">常开</Radio>
                    <Radio :label="2">常闭</Radio>
                </RadioGroup>
            </div>
            <div class="item">
                <span>识别模式</span>
                <RadioGroup v-model="currentAlarmDevice.recognition_mode">
                    <Radio :label="1">一直识别</Radio>
                    <Radio :label="2">次数识别</Radio>
                    <Radio :label="3">单张识别</Radio>
                </RadioGroup>
            </div>
            <div class="item">
                <span>比对相似度</span>
                <InputNumber :max="100" :min="1" v-model="currentAlarmDevice.similarity_set"></InputNumber>
            </div>
            <div class="item">
                <span>布防时间段</span>
                <TimePicker format="HH:mm" :v-model="timeRange" type="timerange" placement="bottom-end" placeholder="请选择时间段" style="width: 150px"></TimePicker>
            </div>
        </div>
        <div slot="footer">
            <Button @click="alarmSettingModal=false">取消</Button>
            <Button type="primary" @click="saveAlarm">确定</Button>
        </div>
    </Modal>
    <!-- 网络信息 -->
    <Modal @on-visible-change="status=>{if(!status){ this.$refs['netForm'].resetFields()}}" class-name="net-setting-dialog" width="600" v-model="netSettingModal" title="网络信息">
        <Form ref="netForm" :model="currentNetDevice" :rules="netRules" inline :label-width="120">
            <FormItem label="IP地址" prop="device_ip">
                <Input type="text" v-model="currentNetDevice.device_ip" placeholder="">
                </Input>
            </FormItem>
            <FormItem label="子网掩码" prop="subnet_mask">
                <Input type="text" v-model="currentNetDevice.subnet_mask" placeholder="">
                </Input>
            </FormItem>
            <FormItem label="网关" prop="gateway">
                <Input type="text" v-model="currentNetDevice.gateway" placeholder="">
                </Input>
            </FormItem>
            <FormItem label="首选DNS地址" prop="preferred_dns">
                <Input type="text" v-model="currentNetDevice.preferred_dns" placeholder="">
                </Input>
            </FormItem>
            <FormItem label="备用DNS地址" prop="standby_dns">
                <Input type="text" v-model="currentNetDevice.standby_dns" placeholder="">
                </Input>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button @click="netSettingModal=false">取消</Button>
            <Button type="primary" @click="saveNet">确定</Button>
        </div>
    </Modal>
  </div>
</template>

<script>
import ME from "../../controllers/ipcSetting";
import {
  emptyStudentFeature,
  syncStudentFeature
} from "../../controllers/user";
import iconEdit from "../../images/edit.png";
import iconPwd from "../../images/password.png";
import iconStop from "../../images/stop.png";
import iconRestart from "../../images/restart.png";
import AddIPCModal from "./components/AddIpcModal";
import AddGuardModal from "./components/AddGuardModal";
import iconDelete from "../../images/delete.png";

import AddIPCModalDahua from "./components/AddIpcModal-Dahua";
import AddIPCModalHobotSmartX1 from "./components/AddIpcModal-HobotSmart-X1";
// import AddIPCModalJulongSmart3519 from "./components/AddIpcModal-JulongSmart-3519";
import AddIPCModalJulongJHD23 from "./components/AddIpcModal-Julong-jHD23";
import AddIPCModalHobotSmartX1S from "./components/AddIpcModal-HobotSmart-X1S";
import AddIPCModalRTSP from "./components/AddIpcModal-RTSP";

import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip";
import Btn from "../../../node_modules/iview/src/components/button/button";
const ipValidator = function(obj,val,cb){
    const ipRegex =  /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
    if(!val){
        return cb(false)
    }else if(!ipRegex.test(val)){
        return cb(false)
    }
    return cb()
}
const uuidValidator = function(obj,val,cb){
    const uuidRegex =  /^[\da-z]{1,50}$/i
    if(!val){
        return cb(false)
    }else if(!uuidRegex.test(val)){
        return cb(false)
    }
    return cb()
}
export default {
  components: {
    AddIPCModal,
    AddGuardModal,
    AddIPCModalDahua,
    AddIPCModalHobotSmartX1,
    // AddIPCModalJulongSmart3519,
    AddIPCModalHobotSmartX1S,
    AddIPCModalRTSP,
    AddIPCModalJulongJHD23,
    Tooltip,
    Btn
  },
  data() {
    return {
      queryForm:{
        ipc_id:'',
        d_nm:''
      },
      ipcColumn: [
        {
          title: "ID",
          align: "center",
          key: "ipc_id",
          width:160,
        },
        {
          title: "设备编号",
          align: "center",
          key: "device_num",
          width:160,
        },
        {
          title: "名称",
          align: "center",
          key: "ipc_name",
          width:200,
        },
        {
          title: "类型",
          align: "center",
          key: "ipc_type",
          width:160,
        },
        {
          title: "IP",
          align: "center",
          key: "ipc_ip",
          width:160,
        },
        {
          title: "设备组",
          align: "center",
          key: "device_group",
          width:160,
        },
        {
          title: "设备地址",
          align: "center",
          key: "d_address",
          width:200,
        },
        {
          title: "状态",
          align: "center",
          key: "ipc_capture_status",
          width:200,
          render: (h, { row, column, index }) => {
            let state_normal = row[column.key] == "0" ? true : false;
            return h(
              "div",
              {
                style: {
                  color: state_normal ? "#038cd6" : "#ed3f14"
                }
              },
              row[column.key] == "0" ? '正常' : row[column.key] == "3" ? "等待验证" : row[column.key] == "2" ? "关闭或正在重启" : "未开启"
            );
          }
        },
        // {
        //   title: "是否作为门禁",
        //   align: "center",
        //   key: "ipc_sw_flag",
        //   width:200,
        //   render: (h, { row, column, index }) => {
        //     return row[column.key] == "1" ? "是" : "否";
        //   }
        // },
        {
          title: "操作",
          align: "center",
          minWidth: 300,
          fixed:'right',
          render: (h, { row, column, index }) => {
            const isJulong = row.ipc_type === 'Julong_jHD23'
            const isRun = row.ipc_capture_status === 0
            return (
              <div class="operate-column">
                  <Btn
                    type="text"
                    onClick={() => this.editIpcModal(row)}
                  >编辑</Btn>
                  <Btn
                    type="text"
                    style={{ display:isJulong?'':'none'}}
                    onClick={() => this.viewDeviceDetail(row)}
                  >设备详情</Btn>
                  <Btn 
                    style="display:none"
                    type="text" 
                    size="small" 
                    disabled={!isRun} 
                    onClick={() => this.editAlarm(row)}>
                    人脸识别报警设置
                  </Btn>
                  <Btn 
                    style="display:none"
                    type="text" 
                    size="small" 
                    disabled={!isRun} onClick={() => this.editNet(row)}>
                    网络信息
                  </Btn>
                  <Btn
                    type="text"
                    style={{ display:isJulong?'none':''}}
                    onClick={() => this.showAddGuardModal(row)}
                  >门禁设置</Btn>
                  <Btn
                    type="text"
                    onClick={() => this.handleDelIpc(row)}
                  >删除</Btn>
                  <Btn
                    type="text"
                    style={{ display:isRun?'':'none'}}
                    onClick={() => this.handleRestartIpc(row)}
                  >重启</Btn>
                  <Btn
                    type="text"
                    style={{ display:isJulong?'none':isRun?'':'none' }}
                    onClick={() => this.handleStopIpc(row)}
                  >停止</Btn>
              </div>
            );
          }
        }
      ],
      ipcDataList: [],
      ipcModalShow: false,
      editIpcFlag: false,
      ipcData: {},
      ipcDataTimer:null,

      // 巨龙设备信息
      // addDeviceModal:false,
      deviceDetailModal:false,
      alarmSettingModal:false,
      netSettingModal:false,
      currentDevice:{},
      currentAlarmDevice:{},
      currentNetDevice:{},
      timeRange:'',
      netRules:{
          device_ip:[
              { required:true, message:'请输入ip地址', trigger: 'blur'},
              { message:'ip地址格式错误', validator: ipValidator, trigger: 'blur'},
          ],
          subnet_mask:[
              { required:true, message:'请输入子网掩码', trigger: 'blur'},
              { message:'子网掩码格式错误', validator: ipValidator, trigger: 'blur'},
          ],
          gateway:[
              { required:true, message:'请输入网关', trigger: 'blur'},
              { message:'网关格式错误', validator: ipValidator, trigger: 'blur'},
          ],
          preferred_dns:[
              { required:true, message:'请输入首选DNS地址', trigger: 'blur'},
              { message:'首选DNS地址格式错误', validator: ipValidator, trigger: 'blur'},
          ],
          standby_dns:[
              { required:true, message:'请输入备用DNS地址', trigger: 'blur'},
              { message:'备用DNS地址格式错误', validator: ipValidator, trigger: 'blur'},
          ]
      }
    };
  },
  created() {
    this.loadTableData();
    // this.ipcDataTimer = window.setInterval(()=>{
    //   this.loadTableData()
    // },10*1000)
  },
  beforeDestroy(){
    this.ipcDataTimer && window.clearInterval(this.ipcDataTimer)
  },
  computed: {},
  methods: {
    loadTableData() {
      ME.loadIpcList(this.queryForm).then(json => {
        this.ipcDataList = json.data;
      });
    },
    showAddIpcModal() {
      this.$refs["addIpc"].showAsAdd();
    },
    editIpcModal(data) {
      //编辑
      //TODO type 为摄像机类型
      // let type=""
      // switch (type){
      //     case 'dahua':
      //         this.$refs['addIpc'].showAsUpdate(data)
      //         break
      // }
      let type = data.ipc_type;

      switch (type) {
        case "DahuaNormal":
          this.$refs["addIPCDahua"].showAsUpdate(data);
          break;
        case "HobotSmart_X1":
          this.$refs["addIPCHobotSmartX1"].showAsUpdate(data);
          break;
        // case "JulongSmart_3519":
        //   this.$refs["addIPCJulongSmart3519"].showAsUpdate(data);
        //   break;
        case "Julong_jHD23":
          this.$refs['addIPCModalJulongJHD23'].showAsUpdate(data);
          break;
        case "HobotSmart_X1S":
          this.$refs["addIPCHobotSmartX1S"].showAsUpdate(data);
          break;
        case "RTSP_Video":
          this.$refs["addIPCHobotRTSP"].showAsUpdate(data);
          break;
      }
    },
    onIpcUpdate() {
      this.loadTableData();
    },
    showAddGuardModal(data) {
      this.$refs["addGuard"].showAsUpdate(data.ipc_id, data.ipc_sw_flag);
    },
    handleDelIpc(data) {
      let name = data.ipc_name;
      let ipc_id = data.ipc_id;
      this.$Modal.confirm({
        title: "确认",
        content: "删除IPC【" + name + "】？",
        onOk: () => {
          // 先删除特征
          ME.deleteIpc({ ipc_id: ipc_id }).then(res => {
            if (res.code == 0) {
              this.$Message.success("删除成功");
              this.onIpcUpdate();
            }
          });
        }
      });
    },
    handleAddIPC(data) {
      switch (data) {
        case "DahuaNormal":
          this.$refs["addIPCDahua"].showAsAdd();
          break;
        case "HobotSmart_X1":
          this.$refs["addIPCHobotSmartX1"].showAsAdd();
          break;
        // case "JulongSmart_3519":
        //   this.$refs["addIPCJulongSmart3519"].showAsAdd();
        //   break;
        case "Julong_jHD23":
          this.$refs['addIPCModalJulongJHD23'].showAsAdd();
          break;
        case "HobotSmart_X1S":
          this.$refs["addIPCHobotSmartX1S"].showAsAdd();
          break;
        case "RTSP_Video":
          this.$refs["addIPCHobotRTSP"].showAsAdd();
          break;
      }
    },
    handleStopIpc(data) {
      let name = data.ipc_name;
      let ipc_id = data.ipc_id;
      this.$Modal.confirm({
        title: "确认",
        content: "停止IPC【" + name + "】？",
        onOk: () => {
          // 先删除特征
          ME.stopIpc({ ipc_id: ipc_id }).then(res => {
            if (res.code == 0) {
              this.$Message.success(res.msg);
              this.onIpcUpdate();
            }
          });
        }
      });
    },
    handleRestartIpc(data) {
      let name = data.ipc_name;
      let ipc_id = data.ipc_id;
      this.$Modal.confirm({
        title: "确认",
        content: "重启IPC【" + name + "】？",
        onOk: () => {
          const params = {
            ipc_id
          }
          if(data.ipc_type === 'Julong_jHD23'){
            params.ipc_type = 'Julong_jHD23'
          }
          ME.restartIpc(params).then(res => {
            if (res.code == 0) {
              this.$Message.success(res.msg);
              this.onIpcUpdate();
            }
          });
        }
      });
    },
    // 特征值库
    emptyFeature(){
      this.$Modal.confirm({
        title: "确认",
        content: "清空特征值底库吗？",
        onOk: () => {
          emptyStudentFeature().then(res => {
            if (res.code == 0) {
              this.$Message.success(res.msg);
            }
          });
        }
      });
    },
    syncFeature(){
      this.$Modal.confirm({
        title: "确认",
        content: "同步特征值底库吗？",
        onOk: () => {
          syncStudentFeature().then(res => {
            if (res.code == 0) {
              this.$Message.success(res.msg);
            }
          });
        }
      });
    },
    // 巨龙设备
    editAlarm(row){
      this.currentAlarmDevice = {
          device_uuid:row.device_uuid,
          alarm_switch:row.alarm_switch||2,
          black_alarm_switch:row.black_alarm_switch||2,
          white_alarm_switch:row.white_alarm_switch||2,
          io_switch:row.io_switch||2,
          io_type:row.io_type||2,
          alarm_duration:row.alarm_duration,
          io_status_type:row.io_status_type||2,
          recognition_mode:row.recognition_mode,
          similarity_set:row.similarity_set,
          alarm_start_time:row.alarm_start_time,
          alarm_end_time:row.alarm_end_time
      }
      this.timeRange = [row.alarm_start_time,row.alarm_end_time]
      this.alarmSettingModal = true
    },
    saveAlarm(){
        if(this.timeRange&&!this.timeRange[0]){
            return this.$Message.warning('请选择布防时间段')
        }
        this.currentAlarmDevice.alarm_start_time = this.timeRange[0]
        this.currentAlarmDevice.alarm_end_time = this.timeRange[1]
        for(let key of Object.keys(this.currentAlarmDevice)){
            if(!this.currentAlarmDevice[key]) return this.$Message.warning('请将信息填写完整')
        }
        this.alarmSettingModal = false
        ME.updateAlarm(this.currentAlarmDevice).then(res=>{
            const { code } = res
            if(code === 0) {
                this.getDevices();
                return this.$Message.success('更新成功')
            }
        })
    },
    saveAlarm(){
        if(this.timeRange&&!this.timeRange[0]){
            return this.$Message.warning('请选择布防时间段')
        }
        this.currentAlarmDevice.alarm_start_time = this.timeRange[0]
        this.currentAlarmDevice.alarm_end_time = this.timeRange[1]
        for(let key of Object.keys(this.currentAlarmDevice)){
            if(!this.currentAlarmDevice[key]) return this.$Message.warning('请将信息填写完整')
        }
        this.alarmSettingModal = false
        ME.updateAlarm(this.currentAlarmDevice).then(res=>{
            const { code } = res
            if(code === 0) {
                this.getDevices();
                return this.$Message.success('更新成功')
            }
        })
    },
    editNet(row){
        this.currentNetDevice = {
            device_uuid:row.device_uuid,
            device_ip:row.device_ip,
            subnet_mask: row.subnet_mask,
            gateway: row.gateway,
            preferred_dns: row.preferred_dns,
            standby_dns: row.standby_dns
        }
        this.netSettingModal = true
    },
    saveNet(){
        for(let key of Object.keys(this.currentNetDevice)){
            if(!this.currentNetDevice[key]) return this.$Message.warning('请将信息填写完整')
        }
        this.$refs['netForm'].validate(valid=>{
            if(valid){
                ME.updateNet(this.currentNetDevice).then(res=>{
                    this.netSettingModal = false
                    const { code } = res
                    if(code === 0) {
                        this.getDevices()
                        return this.$Message.success('更新成功')
                    }
                })
            }
        })
    },
    viewDeviceDetail(row){
      this.currentDevice = row
      this.deviceDetailModal = true
    },
  }
};
</script>
